package com.hanxiaozhang.system.controller;

import com.hanxiaozhang.annotation.LogAnnotation;
import com.hanxiaozhang.constant.ModuleTypeEnum;
import com.hanxiaozhang.redis.util.RedisUtil;
import com.hanxiaozhang.redis.util.CacheUtil;
import com.hanxiaozhang.result.Result;
import com.hanxiaozhang.result.ResultCode;
import com.hanxiaozhang.security.CurrentUserUtil;
import com.hanxiaozhang.system.dto.RouterDTO;
import com.hanxiaozhang.system.service.MenuService;
import com.hanxiaozhang.system.service.UserService;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.security.Principal;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 〈一句话功能简述〉<br>
 * 〈登录控制器〉
 *
 * @author hanxinghua
 * @create 2020/10/15
 * @since 1.0.0
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private ConsumerTokenServices consumerTokenServices;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisBaseUtil;

    @Autowired
    private CacheUtil cacheUtil;


    //        String json ="[{\"path\":\"/system\",\"name\":\"system\",\"icon\":\"setting\",\"routes\":[{\"name\":\"dept\",\"icon\":\"setting\",\"path\":\"/system/dept\",\"component\":\"/system/dept\"}]},{\"name\":\"form\",\"path\":\"/form\",\"icon\":\"form\",\"routes\":[{\"name\":\"basic-form\",\"icon\":\"smile\",\"path\":\"/form/basic-form\",\"component\":\"/form/basic-form\"},{\"name\":\"step-form\",\"icon\":\"smile\",\"path\":\"/form/step-form\",\"component\":\"/form/step-form\"},{\"name\":\"advanced-form\",\"icon\":\"smile\",\"path\":\"/form/advanced-form\",\"component\":\"/form/advanced-form\",\"permission\":[{\"name\":\"添加\",\"key\":\"key-btn1\"},{\"name\":\"编辑\",\"key\":\"key-btn2\"}]}]},{\"path\":\"/list\",\"icon\":\"table\",\"name\":\"list\",\"routes\":[{\"path\":\"/list/search\",\"name\":\"search-list\",\"component\":\"/list/search\",\"routes\":[{\"name\":\"articles\",\"icon\":\"smile\",\"path\":\"/list/search/articles\",\"component\":\"/list/search/articles\",\"permission\":[{\"name\":\"添加\",\"key\":\"key-btn3\"},{\"name\":\"编辑\",\"key\":\"key-btn4\"}]},{\"name\":\"projects\",\"icon\":\"smile\",\"path\":\"/list/search/projects\",\"component\":\"/list/search/projects\"},{\"name\":\"applications\",\"icon\":\"smile\",\"path\":\"/list/search/applications\",\"component\":\"/list/search/applications\"}]},{\"name\":\"table-list\",\"icon\":\"smile\",\"path\":\"/list/table-list\",\"component\":\"/list/table-list\"},{\"name\":\"basic-list\",\"icon\":\"smile\",\"path\":\"/list/basic-list\",\"component\":\"/list/basic-list\"},{\"name\":\"card-list\",\"icon\":\"smile\",\"path\":\"/list/card-list\",\"component\":\"/list/card-list\"}]}]";

    /**
     * 获取该用户的菜单
     *
     * @return
     */
    @LogAnnotation(operation = "获取菜单路由",moduleName = ModuleTypeEnum.SYSTEM)
    @GetMapping("/router")
    public Result router() {
        List<RouterDTO> routerDTOS = menuService.listRouterByUserId(CurrentUserUtil.getUserId());
        return Result.success(routerDTOS);
    }


    /**
     * 登出
     * Tips：这里不能使用 @LogAnnotation，现在保存日志的方法有权限控制，而且需要从token获取用。
     *
     * @param token
     * @return
     */
    @GetMapping("/token/logout")
    public Result logout(String token) {
        Long userId = CurrentUserUtil.getUserId();
        if (consumerTokenServices.revokeToken(token)) {
            cacheUtil.delRouterAndCurUserByUserId(userId);
            return Result.success();
        }
        return Result.error(ResultCode.USER_LOGOUT_ERROR);
    }


    /**
     * 当前用户
     *
     * @return
     */
    @GetMapping("/currentUser")
    public Result currentUser() {
        return Result.success(userService.getCurrentUser(CurrentUserUtil.getUserId()));
    }


    /**
     * 当前用户
     *
     * @param user
     * @return
     */
    @GetMapping("/token/user")
    public Principal user(Principal user) {
        return user;
    }

    /**
     * 验证码
     *
     * @return
     */
    @GetMapping("/captcha")
    public Result captcha() {

        String captchaKey = "captcha_" + UUID.randomUUID();
        // 三个参数分别为宽、高、位数
        SpecCaptcha captcha = new SpecCaptcha(130, 60, 4);
        // 设置字体 有默认字体，可以不用设置
        captcha.setFont(new Font("Verdana", Font.PLAIN, 32));
        // 设置类型，纯数字、纯字母、字母数字混合
        captcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        log.info("key: [{}] ,code: [{}]", captchaKey, captcha.text());
        // 存入Redis ，默认两分钟
        redisBaseUtil.set(captchaKey, captcha.text(), 2, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<String, Object>(4);
        map.put("captchaKey", captchaKey);
        map.put("image", captcha.toBase64());
        return Result.success(map);

    }


}
